'use strict';

const BaseService = require('../base');
const { OrderStatusEnum, OrderPaymentEnum} = require('../../utils/enum');
const dayjs = require('dayjs');
/**
 * 生成订单号
 * @return {string}
 */
function generateOrderNo() {
    const now = dayjs();
    // 生成格式：年月日时分秒+4位随机数
    return 'ON' + now.format('YYYYMMDDHHmmss') + Math.floor(Math.random() * 10000).toString().padStart(4, '0');
}

class OrderService extends BaseService {
    static get modelName() {
        return 'Business.Order';
    }
    getPageInclude() {
        return [
            {
                model: this.ctx.model.Business.User,
                as: 'user',
            },
            {
                //orderItems
                model: this.ctx.model.Business.OrderItem,
                as: 'orderItems',
            }
        ]
    }
    getListInclude() {
        return this.getPageInclude()
    }
    getDetailInclude() {
        return this.getPageInclude()
    }
    /**
     * 创建订单
     * @param {Object} orderData - 订单数据
     * @return {Promise<*>}
     */
    async create(orderData) {
        const { ctx } = this;
        /**
         * 校验用户
         */
        if (!orderData.user_id) throw new Error('用户不存在');
        // 检查用户是否存在
        const user = await ctx.model.Business.User.findOne({
            where: {
                id: orderData.user_id
            }
        })
        if (!user) {
            throw new Error('用户不存在');
        }
        if (!user.status) {
            throw new Error('用户已禁用');
        }
        const transaction = await ctx.model.transaction();
        try {
            // 1. 生成订单号
            const orderNo = generateOrderNo();
            // 2. 创建主订单
            const createData = {
                order_no: orderNo,
                ...orderData,
                status: orderData.payment_amount > 0 ? OrderStatusEnum.PENDING : OrderStatusEnum.PAID
            }
            // 4. 创建订单
            const order = await ctx.model.Business.Order.create(createData, { transaction });
            for (let i = 0; i < orderData.goods.length; i++) {
                const { sku, product, count } = orderData.goods[i];
                // 5. 创建订单商品
                await ctx.model.Business.OrderItem.create({
                    order_id: order.id,
                    product_id: product.id,
                    product_sku_id: sku.id,
                    product_name: product.name,
                    product_cover: product.cover,
                    sku_spec: sku.spec_combination,
                    price: sku.price,
                    count,
                    total_amount: sku.price * count,
                }, {
                    transaction
                })

                // 增加销售数量
                await ctx.model.Business.Product.update({
                    sales: ctx.model.Sequelize.literal(`sales + ${count}`)
                }, {
                    where: {
                        id: product.id
                    },
                    transaction
                })
            }
            await transaction.commit();
            // 6. 返回订单信息
            return order
        } catch (error) {
            console.log(error)
            await transaction.rollback();
            throw error;
        }
    }
    /**
     * 取消订单
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async cancel(params) {
        const { ctx } = this;
        const { id } = params;
        const transaction = await ctx.model.transaction();

        try {
            // 1. 查询订单
            const order = await this.ctx.model.Business.Order.findOne({
                where: {
                    id,
                },
            });

            if (!order) {
                throw new Error('订单不存在');
            }
            const user = await this.ctx.model.Business.User.findOne({
                where: {
                    id: order.user_id
                }
            })
            if (!user) {
                throw new Error('用户不存在');
            }
            // 2. 判断订单状态
            if (order.status !== OrderStatusEnum.PENDING) {
                throw new Error('只有未支付的订单才能取消');
            }
            // 5. 更新订单状态
            await order.update({
                status: OrderStatusEnum.CANCELLED,
                cancel_time: new Date(),
            }, { transaction });

            await transaction.commit();
            return true;
        } catch (error) {
            await transaction.rollback();
            throw error;
        }
    }

    /**
     * 设置订单价格
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async setPrice(params) {
        const { ctx } = this;
        const { order_id, store_id, amount } = params;
        const transaction = await ctx.model.transaction();

        try {
            // 1. 查询订单
            const order = await this.ctx.model.Business.Order.findOne({
                where: {
                    id: order_id,
                    store_id: store_id
                },
            });

            if (!order) {
                throw new Error('订单不存在或无权限操作');
            }

            // 2. 验证工坊权限
            const store = await this.ctx.model.Business.Store.findOne({
                where: {
                    id: store_id
                }
            });

            if (!store) {
                throw new Error('工坊不存在');
            }

            // 3. 判断订单状态
            if (order.status !== OrderStatusEnum.PENDING_PRICING && order.status !== OrderStatusEnum.PENDING) {
                throw new Error('只有待定价或待支付的订单才能设置价格');
            }

            // 4. 验证价格
            const price = parseFloat(amount);
            if (isNaN(price) || price <= 0) {
                throw new Error('价格必须大于0');
            }

            // 5. 更新订单价格和状态
            await order.update({
                amount: price,
                payment_amount: price,
                status: OrderStatusEnum.PENDING,
                update_time: new Date(),
            }, { transaction });

            await transaction.commit();
            return true;
        } catch (error) {
            await transaction.rollback();
            throw error;
        }
    }
    
    /**
     * 申请退款
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async refund(params) {
        const { ctx } = this;
        const { id, refund_reason, is_admin = false } = params;
        const transaction = await ctx.model.transaction();

        try {
            // 查询订单
            const order = await this.ctx.model.Business.Order.findOne({
                where: { id }
            });

            if (!order) {
                throw new Error('订单不存在');
            }
            // 判断订单状态
            if(!is_admin) {
                if (order.status !== OrderStatusEnum.PAID && order.status !== OrderStatusEnum.REFUNDED) {
                    throw new Error('只有未确认的订单才能申请退款');
                }
            }
            const refund_amount = params.refund_amount || order.payment_amount
            // const refund_amount = 0.01
            let refundForm = {
                status: OrderStatusEnum.REFUNDING,
                refund_time: new Date(),
                refund_reason,
                refund_amount
            }
            // 更新订单状态
            await order.update(refundForm, { transaction });

            await transaction.commit();

            return true;
        } catch (error) {
            await transaction.rollback();
            throw error;
        }
    }

    /**
     * 处理退款
     */
    async refundConfirm(data) {
        const { id, refund_remark, refund_amount, approve } = data;

        // 查询订单
        const order = await this.ctx.model.Business.Order.findOne({
            where: { id }
        });

        if (!order) {
            throw new Error('订单不存在');
        }
        let refund_amount_int = Number(refund_amount)
        if (!approve) {
            // 不同意退款
            await order.update({
                status: OrderStatusEnum.REFUND_FAILED,
                refund_time: new Date(),
                refund_remark,
            });
            return true
        } else {
            // 同意退款
            if (refund_amount_int >= order.payment_amount) {
                refund_amount_int = order.payment_amount
            }

            // 创建事务处理退款
            await order.update({
                status: refund_amount_int ? OrderStatusEnum.REFUNDING : OrderStatusEnum.REFUNDED,
            });
            // 实付满额才退微信支付
            if (refund_amount_int) {
                console.log('refund_amount_int',refund_amount_int)
                console.log('order.payment_amount',order.payment_amount)
                // 调用退款接口
                await this.ctx.service.business.orderRefund.processRefund({
                    order_no: order.order_no,
                    refund_remark,
                    refund_amount: refund_amount_int,
                    payment_amount: order.payment_amount
                });
            }

        }
        return true
    }

    /**
     * 确认旅游行程
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async confirm(params) {
        const { id, confirm_remark } = params;
        const transaction = await this.ctx.model.transaction();

        try {
            // 查询订单
            const order = await this.ctx.model.Business.Order.findOne({
                where: { id }
            });

            if (!order) {
                throw new Error('订单不存在');
            }

            // 判断订单状态
            if (order.status !== OrderStatusEnum.PAID) {
                throw new Error('只有待确认的订单才能确认行程');
            }

            // 更新订单状态
            await order.update({    
                status: OrderStatusEnum.SHIPPED,
                update_time: new Date(),
            }, { transaction });

            await transaction.commit();
            return true;
        } catch (error) {
            await transaction.rollback();
            throw error;
        }
    }

    /**
     * 完成旅游行程
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async complete(params) {
        const { id, complete_remark } = params;
        const transaction = await this.ctx.model.transaction();

        try {
            // 查询订单
            const order = await this.ctx.model.Business.Order.findOne({
                where: { id }
            });

            if (!order) {
                throw new Error('订单不存在');
            }

            // 判断订单状态
            if (order.status !== OrderStatusEnum.SHIPPED) {
                throw new Error('只有已确认的订单才能完成行程');
            }

            // 更新订单状态
            await order.update({
                status: OrderStatusEnum.COMPLETED,
                update_time: new Date(),
            }, { transaction });

            await transaction.commit();
            return true;
        } catch (error) {
            await transaction.rollback();
            throw error;
        }
    }

    /**
     * 删除订单
     * @param {Object} params - 参数
     * @return {Promise<boolean>}
     */
    async delete(id) {
        // 查询订单
        const order = await this.model.findOne({
            where: { id }
        });

        if (!order) {
            throw new Error('订单不存在');
        }

        // 只有已取消、已退款的订单可以删除
        if (![OrderStatusEnum.CANCELLED].includes(order.status)) {
            throw new Error('只有已取消的订单才能删除');
        }
        // 软删除订单
        await super.delete(id, 0)
        return true;
    }
}

module.exports = OrderService;
